import { Service } from 'egg';
import {
  openFlow,
  closeFlow,
  createFlowDefine,
  getFlowDefine,
  saveFlow,
} from '../sql/flow';

export default class flow extends Service {
  async openFlow(params: { [key: string]: any }) {
    const { ctx, app } = this;
    if (!params.flowId) {
      const flowId = 'flow_' + ctx.helper.getUuid();
      Object.assign(params, { flowId });
      const formatParams = ctx.helper.toJsonString(params);
      const { sql, param } = ctx.helper.formatSql(
        createFlowDefine,
        formatParams,
      );
      ctx.logger.info('createFlowDefine:', sql, formatParams);
      await app.mysql.query(sql, param);
    }
    const { sql, param } = ctx.helper.formatSql(openFlow, params);
    ctx.logger.info('openFlow:', sql, params);
    await app.mysql.query(sql, param);
    return {
      flowId: params.flowId,
      flowOpened: 1,
    };
  }
  async closeFlow(params: { [key: string]: any }) {
    const { ctx, app } = this;
    const { sql, param } = ctx.helper.formatSql(closeFlow, params);
    ctx.logger.info('closeFlow:', sql, params);
    await app.mysql.query(sql, param);
    return null;
  }
  async getFlowDefine(params: { [key: string]: any }) {
    const { ctx, app } = this;
    const { sql, param } = ctx.helper.formatSql(getFlowDefine, params);
    ctx.logger.info('getFlowDefine:', sql, params);
    const res = await app.mysql.query(sql, param);
    const data = ctx.helper.toJsonObj(res[0]);
    return data;
  }
  async saveFlow(params: { [key: string]: any }) {
    const { ctx, app } = this;
    const formatParams = ctx.helper.toJsonString(params);
    const { sql, param } = ctx.helper.formatSql(saveFlow, formatParams);
    ctx.logger.info('saveFlow:', sql, param);
    await app.mysql.query(sql, param);
    return null;
  }
}
